# coding=utf-8
from flask import Flask, jsonify, render_template, json
# from py2neo import Graph
from neo4j import GraphDatabase

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "tianxin"))  # 认证连接数据库

app = Flask(__name__)  # flask框架必备


def buildNodes(nodeRecord):  # 构建web显示节点
    data = {"id": nodeRecord._id, "label": list(nodeRecord._labels)[0]}  # 将集合元素变为list，然后取出值
    data.update(dict(nodeRecord._properties))

    return {"data": data}


def buildEdges(relationRecord):  # 构建web显示边
    data = {"source": relationRecord.start_node._id,
            "target": relationRecord.end_node._id,
            "relationship": relationRecord.type}

    return {"data": data}


# @app.route('/')  # 建立路由，指向网页
# def index():
#     return render_template('index.html')


@app.route('/')  # 两个路由指向同一个网页，返回图的节点和边的结构体
def get_graph():
    with driver.session() as session:
        datas = []
        links = []
        nodes = list(map(buildNodes, session.run("MATCH (n) RETURN n").value()))
        edges = list(map(buildEdges, session.run("MATCH ()-[r]->() RETURN r").value()))
        print(nodes)
        print(edges)
        for node, edge in zip(nodes, edges):
            # print(type(str(node["data"]["id"])))
            datas.append({
                "name": str(node["data"]["name"]),
                "symbolSize": 50,
                "itemStyle": {'normal': {'color': '#82b1ff'}}})
            links.append({
                "source": session.run(
                    "MATCH (r) WHERE id(r) = " + str(edge["data"]["source"]) + " RETURN r.name").value()[0],
                "target": session.run(
                    "MATCH (r) WHERE id(r) = " + str(edge["data"]["target"]) + " RETURN r.name").value()[0]})
    # return jsonify({"datas": datas, "links": links})
    print(datas)
    print(links)
    return render_template('index.html', datas=datas, links=links)


if __name__ == '__main__':
    app.config['JSON_AS_ASCII'] = False
    app.run(debug=True)  # flask框架必备
